package org.geekbang.thinking.in.spring.bean.definition;

import org.geekbang.thinking.in.spring.bean.factory.DefaultUserFactory;
import org.geekbang.thinking.in.spring.bean.factory.UserFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;

/**
 * Bean 初始化 Demo
 */
@Configuration //不加也一样
public class BeanInitiallizationDemo {

    public static void main(String[] args) {
        //创建 BeanFactory 容器
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        //注册 Configuration Class (配置类)
        applicationContext.register(BeanInitiallizationDemo.class);

        //启动 Spring 应用上下文(XML配置方式不需要)
        applicationContext.refresh();
        //非延迟初始化在 Spring 应用上下文启动完成前被初始化
        //延迟初始化在 Spring 应用上下文启动完成后被初始化，如果没有人getBean不初始化
        System.out.println("Spring 上下文已启动...");
        //依赖查找 UserFactory
        UserFactory userFactory = applicationContext.getBean(UserFactory.class);
        System.out.println(userFactory);
        //applicationContext.close() 方法触发了 Bean 的销毁动作
        System.out.println("Spring 上下文准备关闭...");
        //显式的关闭 Spring 应用上下文
        applicationContext.close();
        System.out.println("Spring 上下文已关闭...");
    }

    @Bean(initMethod = "initUserFactory", destroyMethod = "doDestroy")
    public UserFactory userFactory(){
        return new DefaultUserFactory();
    }

}
